﻿using System;
using DDDProjectSample.Domain;
using DDDProjectSample.Domain.Repositories;
using Castle.Facilities.NHibernateIntegration;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Expression;

namespace DDDProjectSample.Infrastructure.Repositories
{
    public class MessageRepository : BaseRepository<Message>, IMessageRepository
    {
        /// <summary>
        /// Creates a new instance of class MessageRepository
        /// </summary>
        /// <param name="sessionManager">The Nhibernate Session Manager</param>
        public MessageRepository(
            ISessionManager sessionManager) : base(sessionManager)
        {
        }

        #region IMessageRepository Members

        public ICollection<Message> FindByTopicId(long topicId)
        {
            using (ISession session = SessionManager.OpenSession())
            {
                return session.CreateCriteria(typeof(Message))
                            .SetFetchMode("Author", FetchMode.Join)
                            .Add(Expression.Eq("Topic.Id", topicId))
                            .AddOrder(Order.Asc("CreationDate"))
                            .List<Message>();
            }
        }

        #endregion
    }
}
